﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using zichan.BLL;
using zichan.Entity;
using zichan.Models;

namespace zichan.Controllers
{
    public class AsseteClassController : BaseController
    {
        // GET: AsseteClass
        public ActionResult Index(string name,string identity, int? page,int? pageSize,int? pageCount,int? selectedPage)
        {
            page = page ?? 1;
            pageSize = pageSize ?? 10;
            if (selectedPage.HasValue)
                page = selectedPage;
            if (pageCount.HasValue)
                page = page <= pageCount ? page : pageCount;
            if (page < 1) page = 1;
            ViewBag.page = page;
            ViewBag.pageSize = pageSize;
            ViewBag.selectedPage = selectedPage;

            List<SelectListItem> items = new List<SelectListItem> { new SelectListItem { Value = "10", Text = "10" }, new SelectListItem { Value = "20", Text = "20" }, new SelectListItem { Value = "50", Text = "50" }, new SelectListItem { Value = "100", Text = "100" } };
            ViewBag.pageSizes = new SelectList(items, "Value", "Text",ViewBag.pageIndex);
            ViewBag.name = name;
            ViewBag.identity = identity;
            return View(AsseteClassService.GetAsseteClassList(name,identity, pageSize.Value, page.Value));
        }
        public ActionResult Create()
        {
            ViewBag.maxSort = AsseteClassService.MaxSort() + 1;
            return View();
        }
        [HttpPost]
        public ActionResult Create(AsseteClassify model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            string err = AsseteClassService.AddAsseteClass(model);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#添加成功";
                ClassLogService.AddLog("资产分类", "添加" + "\"" + model.Name + "," + model.Identity + "\"");
            }
            else
            {
                TempData["alert"] = "error#" + err; 
            }
            return RedirectToAction("Index");
        }
        public ActionResult CreateList()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CreateList(AssetListModel model)
        {
            #region 验证
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            List<string> list = model.nameList.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            int icount = list.Where(o => Regex.Match(o, @"[\w*|\S][\,|，][.*|\S|\s\w+]").ToString() == "").Count();
            if (icount>0)
            {
                ModelState.AddModelError("nameList", "请输入正确格式的数据");
                return View(model);
            }

            //bool b = false; 
            //foreach (string s in list)
            //{
            //    Match result = Regex.Match(s, @"[\w*|\S][\,|，][.*|\S|\s\w+]");
            //    if(result.ToString()=="")
            //    {
            //        b = true;
            //    }
            //}
            //if(b)
            //{
            //    ModelState.AddModelError("nameList", "请输入正确格式的数据");
            //    return View(model);
            //}
            #endregion
            List<string> existName;
            List<string> nameListForLog;
            List<string> existidentity;
            string err = AsseteClassService.AddBatchClass(list, out existName, out nameListForLog, out existidentity);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#添加成功";
                if (existName.Count() > 0 && existidentity.Count() == 0)
                {
                    TempData["alert"] = "error#" + string.Join("、", existName) + "因重命名无法添加";
                }
                if (existName.Count() > 0 && existidentity.Count() > 0)
                {
                    TempData["alert"] = "error#" + string.Join("、", existName) + "因标识重复无法添加";
                }
                if (nameListForLog.Count() > 0)
                {
                    ClassLogService.AddLog("资产分类", "添加" + "\"" + string.Join("、", nameListForLog) + "\"");
                }

            }
            else
                TempData["alert"] = "error#添加失败";

            return RedirectToAction("Index");
        }
        public ActionResult Edit(int id)
        {
            AsseteClassify assetClass = AsseteClassService.GetAsseteClass(id);
            if (assetClass == null)
                return HttpNotFound();

            return View(assetClass);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(AsseteClassify model)
        {
            if (!ModelState.IsValid)
                return View(model);
            if (model.Id == 1 && string.IsNullOrEmpty(model.SubIdentity))
            {
                ModelState.AddModelError("SubIdentity", "标识不为空");
                return View(model);
            }
            string oldName = AsseteClassService.GetAsseteClass(model.Id).Name;
            string oldIdentity = AsseteClassService.GetAsseteClass(model.Id).Identity;
            string oldSubIdentity = AsseteClassService.GetAsseteClass(model.Id).SubIdentity;
            string err = AsseteClassService.EditAsseteClass(model);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#修改成功";
                if (model.Id != 1)
                    ClassLogService.AddLog("资产分类", "修改" + "\"" + oldName + "," + oldIdentity + "\"为\"" + model.Name + "," + model.Identity + "\"");
                else
                    ClassLogService.AddLog("资产分类", "修改" + "\"" + oldName + "," + oldIdentity+ "," + oldSubIdentity + "\"为\"" + model.Name + "," + model.Identity+","+model.SubIdentity + "\"");

            }
            else
                TempData["alert"] = "error#" + err;
            return RedirectToAction("index");
        }

        public ActionResult Delete(int id)
        {
            string err = AsseteClassService.RemoveAsseteClass(id);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#删除成功";
            }
            else
                TempData["alert"] = "error#" + err;

            return RedirectToAction("index");
        }
        public ActionResult FieldsIndex(string name, int assetClassId, int? page, int? pageSize, int? pageCount, int? selectedPage)
        {
            page = page ?? 1;
            pageSize = pageSize ?? 10;
            if (selectedPage.HasValue)
                page = selectedPage;
            if (pageCount.HasValue)
                page = page <= pageCount ? page : pageCount;
            if (page < 1) page = 1;
            ViewBag.page = page;
            ViewBag.pageSize = pageSize;
            ViewBag.selectedPage = selectedPage;
            List<SelectListItem> items = new List<SelectListItem> { new SelectListItem { Value = "10", Text = "10" }, new SelectListItem { Value = "20", Text = "20" }, new SelectListItem { Value = "50", Text = "50" }, new SelectListItem { Value = "100", Text = "100" } };
            ViewBag.pageSizes = new SelectList(items, "Value", "Text", ViewBag.pageIndex);

            ViewBag.assetClassId = assetClassId;
            ViewBag.name = name;
            ViewBag.assetName= AsseteClassService.GetAsseteClass(assetClassId).Name;
            return View(FieldsService.GetFieldsList(name,assetClassId,pageSize.Value, page.Value));
        }
        public ActionResult AddFields(int assetClassId)
        {
            ViewBag.maxSort = FieldsService.MaxSort() + 1;
            ViewBag.assetClassId = assetClassId;
            ViewBag.assetName = AsseteClassService.GetAsseteClass(assetClassId).Name;
            return View();
        }
       
        [HttpPost]
        public ActionResult AddFields(AsseteField model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.maxSort = FieldsService.MaxSort() + 1;
                ViewBag.assetClassId = model.AsseteClassId;
                ViewBag.assetName = AsseteClassService.GetAsseteClass(model.AsseteClassId).Name;
                return View(model);
            }
            string err = FieldsService.AddFields(model);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#添加成功";
                ClassLogService.AddLog("资产分类", "添加" + "\"" +AsseteClassService.GetAsseteClass(model.AsseteClassId).Name+",字段:"+ model.Name + "\"");
            }
            else
            {
                TempData["alert"] = "error#"+err;
            }
            return RedirectToAction("FieldsIndex",new { assetClassId=model.AsseteClassId });
        }
        public ActionResult CreateFieldsList(int assetClassId)
        {
            ViewBag.assetClassId = assetClassId;
            ViewBag.assetName= AsseteClassService.GetAsseteClass(assetClassId).Name;
            return View();
        }
        [HttpPost]
        public ActionResult CreateFieldsList(ListModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.assetClassId = model.AssetClassId;
                ViewBag.assetName = AsseteClassService.GetAsseteClass(model.AssetClassId).Name;
                return View(model);
            }
            List<string> list = model.nameList.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            List<string> existName;
            List<string> nameListForLog;
            string err = FieldsService.AddBatchFields(list,model.AssetClassId, out existName, out nameListForLog);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#添加成功";
                if (existName.Count() > 0)
                {
                    TempData["alert"] = "error#" + string.Join("、", existName) + "因重命名无法添加";
                }
                if (nameListForLog.Count() > 0)
                {
                    ClassLogService.AddLog("资产分类", "添加" + "\"" + string.Join("、", nameListForLog) + "\"");
                }
            }
            else
                TempData["alert"] = "error#"+err;

            return RedirectToAction("FieldsIndex", new { assetClassId = model.AssetClassId });
        }
        public ActionResult EditFields(int id)
        {
            AsseteField cabinetClass = FieldsService.GetField(id);
            if (cabinetClass == null)
                return HttpNotFound();

            return View(cabinetClass);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditFields(AsseteField model)
        {
            if (!ModelState.IsValid)
                return View(model);
            string oldName = FieldsService.GetField(model.Id).Name;
            string err = FieldsService.EditFields(model);
            if (string.IsNullOrEmpty(err))
            {
                TempData["alert"] = "success#修改成功";
                string constr = ConfigurationManager.ConnectionStrings["ZichanDBContext"].ConnectionString;
                ConsumateInfoService.EditFieldName(model.Name,model.Id, FieldsService.GetField(model.Id).AsseteClassId,constr);
                ClassLogService.AddLog("资产分类", "修改"+ "\""+AsseteClassService.GetAsseteClass(model.AsseteClassId).Name + ",字段:" + oldName + "\"为\"字段:" + model.Name + "\"");
            }
            else
                TempData["alert"] = "error#" + err;
            return RedirectToAction("FieldsIndex", new { assetClassId = model.AsseteClassId });
        }

        public ActionResult DeleteFields(int id, int assetClassId)
        {
            string err = FieldsService.RemoveFields(id);
            if (string.IsNullOrEmpty(err))
            {
                ConsumateInfoService.DeleteFieldName(id);
                TempData["alert"] = "success#删除成功";
            }
            else
                TempData["alert"] = "error#" + err;

            return RedirectToAction("FieldsIndex", new { assetClassId = assetClassId });
        }
    }
}